<template>
  <div 
    class="video-card" 
    :class="{ 'selectable': selectable, 'selected': selected }" 
    @click="handleCardClick"
  >
    <!-- 视频容器 -->
    <div 
      class="video-container" 
      @mouseenter="handleMouseEnter"
      @mouseleave="handleMouseLeave"
    >
      <div class="video-duration" v-if="displayDuration && !showingControls">{{ displayDuration }}</div>

      <video 
        ref="videoElement"
        :src="videoUrl" 
        muted 
        loop 
        preload="metadata" 
        class="video-element"
        :controls="showingControls"
        @loadedmetadata="handleVideoMetadata"
      ></video>
    </div>
    
    <!-- 视频信息 -->
    <div class="video-info">
      <div class="title-row">
        <h5 class="video-title" :title="displayTitle">{{ displayTitle }}</h5>
        <slot name="checkbox"></slot>
      </div>
      
      <div v-if="videoMetadata.date" class="video-date">
        {{ videoMetadata.date }}
      </div>
      
      <div v-if="videoMetadata.category" class="video-category">
        {{ videoMetadata.category }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, onMounted, onBeforeUnmount } from 'vue';

const props = defineProps({
  videoUrl: {
    type: String,
    required: true
  },
  videoTitle: {
    type: String,
    default: ''
  },
  stats: {
    type: String,
    default: ''
  },
  duration: {
    type: String,
    default: ''
  },
  downloadable: {
    type: Boolean,
    default: false
  },
  selectable: {
    type: Boolean,
    default: false
  },
  selected: {
    type: Boolean,
    default: false
  },
  autoplayOnHover: {
    type: Boolean,
    default: true
  },
  alwaysShowControls: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['metadata', 'click', 'download']);

const videoElement = ref(null);
const showingControls = ref(false);
const extractedDuration = ref(null);

// Extract metadata from video URL
const videoMetadata = computed(() => {
  if (!props.videoUrl) return {};
  
  // Extract filename without extension
  const pathParts = props.videoUrl.split('/');
  const filename = pathParts[pathParts.length - 1];
  const nameWithoutExt = filename.substring(0, filename.lastIndexOf('.')) || filename;
  
  // Extract file extension
  const extension = props.videoUrl.split('.').pop().toLowerCase();
  
  // Extract date if present in the URL (format: YYYY-MM-DD or YYYYMMDD)
  let date = null;
  const datePattern = /\d{4}[-_]?\d{2}[-_]?\d{2}/;
  const dateMatch = props.videoUrl.match(datePattern);
  if (dateMatch) {
    // Format the date string to YYYY-MM-DD
    const rawDate = dateMatch[0].replace(/[-_]/g, '');
    date = `${rawDate.substring(0, 4)}-${rawDate.substring(4, 6)}-${rawDate.substring(6, 8)}`;
  }
  
  // Try to extract category from path/folder structure
  let category = '';
  // Look for folder name between slashes
  const categoryPatterns = [
    /\/([^/]+)\/[^/]+\.\w+$/, // Unix-style paths
    /\\([^\\]+)\\[^\\]+\.\w+$/ // Windows-style paths
  ];
  
  for (const pattern of categoryPatterns) {
    const match = props.videoUrl.match(pattern);
    if (match && match[1]) {
      category = match[1].replace(/[-_]/g, ' ');
      // Capitalize first letter
      category = category.charAt(0).toUpperCase() + category.slice(1);
      break;
    }
  }
  
  // Extract title
  // Remove date pattern if present
  let title = nameWithoutExt.replace(datePattern, '');
  // Clean up the title - replace underscores and hyphens with spaces
  title = title.replace(/[-_]/g, ' ').trim();
  // Capitalize first letter of each word
  title = title.split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
  
  return {
    filename,
    title,
    date,
    category,
    extension
  };
});

// Use prop title if provided, otherwise use extracted title
const displayTitle = computed(() => {
  const title = props.videoTitle || videoMetadata.value.filename || '未命名视频';
  return decodeURIComponent(title)
});

// Use prop duration if provided, otherwise use extracted duration
const displayDuration = computed(() => {
  if (props.duration) return props.duration;
  
  if (extractedDuration.value) {
    const minutes = Math.floor(extractedDuration.value / 60);
    const seconds = Math.floor(extractedDuration.value % 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  }
  
  return '';
});

// 处理鼠标进入
const handleMouseEnter = () => {
  // 显示控件
  showingControls.value = true;
  
  // 如果启用了悬停播放，则开始播放
  if (props.autoplayOnHover) {
    playVideo();
  }
};

// 处理鼠标离开
const handleMouseLeave = () => {
  // 如果不是永久显示控件模式，则隐藏控件
  if (!props.alwaysShowControls) {
    showingControls.value = false;
  }
  
  // 如果启用了悬停播放，则停止播放
  if (props.autoplayOnHover) {
    stopVideo();
  }
};

// 播放视频
const playVideo = () => {
  if (!videoElement.value) return;
  
  videoElement.value.currentTime = 0;
  
  const playPromise = videoElement.value.play();
  if (playPromise !== undefined) {
    playPromise.catch(error => {
      console.warn('自动播放被阻止:', error);
    });
  }
};

// 停止视频播放
const stopVideo = () => {
  if (!videoElement.value) return;
  
  if (!videoElement.value.paused) {
    videoElement.value.pause();
  }
};

// 处理视频元数据加载
const handleVideoMetadata = (event) => {
  if (videoElement.value && videoElement.value.duration) {
    // Store duration for display
    extractedDuration.value = videoElement.value.duration;
    
    emit('metadata', {
      duration: videoElement.value.duration,
      width: videoElement.value.videoWidth,
      height: videoElement.value.videoHeight,
      ...videoMetadata.value  // Include extracted metadata
    });
  }
};

// 处理卡片点击
const handleCardClick = (event) => {
  // 防止点击视频控件时触发卡片点击
  if (event.target.closest('video')) return;
  
  emit('click', {
    ...event,
    videoMetadata: videoMetadata.value
  });
};

// 组件卸载前暂停视频
onBeforeUnmount(() => {
  if (videoElement.value && !videoElement.value.paused) {
    videoElement.value.pause();
  }
});

// 初始化时，如果设置了永久显示控件，则显示控件
onMounted(() => {
  if (props.alwaysShowControls) {
    showingControls.value = true;
  }
});
</script>

<style scoped>
/* 视频卡片基础样式 */
.video-card {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 可选择的卡片样式 */
.video-card.selectable {
  cursor: pointer;
  border: 2px solid transparent;
}

.video-card.selectable:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
}

.video-card.selected {
  border-color: #409EFF;
}

/* 视频容器样式 */
.video-container {
  position: relative;
  width: 100%;
  background-color: #000;
  aspect-ratio: 16/9;
  overflow: hidden;
}

/* 视频元素样式 */
.video-element {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

/* 视频时长标签 */
.video-duration {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 5;
  pointer-events: none;
}

.video-container:hover .video-duration {
  opacity: 0;
}

/* 视频信息样式 */
.video-info {
  padding: 10px;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.video-title {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-grow: 1;
}

.video-date, .video-category {
  font-size: 12px;
  color: #606266;
  margin-bottom: 4px;
}

.video-stats {
  font-size: 12px;
  color: #606266;
  margin-bottom: 8px;
}

.video-actions {
  margin-top: auto;
  display: flex;
  justify-content: flex-end;
}

.download-btn {
  padding: 5px 10px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  width: 100%;
}

.download-btn:hover {
  background: #337ecc;
}
</style>